import 'dart:collection';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:opene/app_constant.dart';
import 'package:opene/app_theme.dart';
import 'package:opene/app_utils.dart';
import 'package:opene/base/base_state.dart';
import 'package:opene/base/loading.dart';
import 'package:opene/base/scan_code.dart';
import 'package:opene/home/authorize_bean.dart';
import 'package:opene/net/network_manager.dart';
import 'package:opene/net/response/base_response.dart';
import 'package:opene/ui/manage/adjust/adjustmodel.dart';
import 'package:opene/ui/manage/adjust/remeasurescreen.dart';
import 'package:opene/ui/manage/adjust/remeasuresubmitscreen.dart';
import 'package:opene/ui/manage/adjust/retallyskuscreen.dart';
import 'package:opene/ui/manage/cyclecount/cclocationscreen.dart';
import 'package:opene/ui/manage/cyclecount/ccskuscreen.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:toast/toast.dart';

class AdjustScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return AdjustScreenPage();
  }
}

class AdjustScreenPage extends StatefulWidget {
  @override
  _AdjustPageState createState() => _AdjustPageState();
}

class _AdjustPageState extends BaseState<AdjustScreen> {
  List<String> adjustStrs = new List();
  List<String> data = new List();

  bool isCycleCount = false;
  bool isMerge = false;

  @override
  String setTitle({String title}) {
    return !Utils.isEmpty(title) ? title : "Adjustment: Category";
  }

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    setAuthorizes();
  }

  Future<void> setAuthorizes() async {
    adjustStrs.add("Re-Tally");
    adjustStrs.add("Re-Measure");
    adjustStrs.add("CycleCount-SKU");
    adjustStrs.add("CycleCount-Location");
    adjustStrs.add("Adjust-LPN");
    adjustStrs.add("Merge");
    adjustStrs.add("Destroy");
    adjustStrs.add("Returns");
    adjustStrs.add("CycleCount-LPN");

    var sp = await SharedPreferences.getInstance();
    var string = sp.getString(Constants.authorize);
    if (Utils.isEmpty(string)) {
      return;
    }
    List<Authorize> authorizes = new List<dynamic>.from(json.decode(string)).map((userJson) => Authorize.fromJson(userJson)).toList();
    if (authorizes == null) {
      return;
    }

    authorizes.forEach((element) {
      if (element.code == "pda_cycleCount") {
        isCycleCount = true;
      }
      if (element.code == "pda_merge") {
        isMerge = true;
      }
    });
    adjustStrs.forEach((value) {
      if (value == "CycleCount-SKU" || value == "CycleCount-Location") {
        if (isCycleCount) {
          data.add(value);
        }
      } else if (value == "Merge") {
        if (isMerge) {
          data.add(value);
        }
      } else {
        data.add(value);
      }
    });

    setState(() {});
    setChange(0);
  }

  @override
  Widget getViewBinding() {
    return Padding(
      padding: const EdgeInsets.only(left: 15, top: 10, right: 15),
      child: SingleChildScrollView(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            GridView.builder(
                shrinkWrap: true,
                gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(maxCrossAxisExtent: 200, childAspectRatio: 8, mainAxisSpacing: 5),
                itemCount: data == null ? 0 : data.length,
                itemBuilder: (BuildContext ctx, index) {
                  return GestureDetector(
                    onTap: () {
                      setChange(index);
                    },
                    child: Row(
                      children: [
                        Icon(
                          type == index ? Icons.radio_button_on : Icons.radio_button_off,
                          size: 20,
                          color: type == index ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333,
                        ),
                        Expanded(
                          child: Text(
                            Utils.getStringisEmpty(data[index]),
                            maxLines: 1,
                            overflow: TextOverflow.ellipsis,
                            style: TextStyle(color: type == index ? MyAppTheme.nearlyBlue : MyAppTheme.color_333333, fontSize: 12.0),
                          ),
                        )
                      ],
                    ),
                  );
                }),

            Visibility(
              visible: codeShow,
              child: Container(
                margin: const EdgeInsets.only(left: 0, top: 5, right: 0, bottom: 0),
                width: double.infinity,
                child: ConstrainedBox(
                  constraints: BoxConstraints(maxHeight: 35),
                  child: TextField(
                    controller: textEditingController,
                    textInputAction: TextInputAction.search,
                    onSubmitted: (String text) {
                      print('Searching for $text');
                      if (Utils.isEmpty(text)) {
                        return;
                      }
                      setSubmitNext(text);
                    },
                    // autofocus: true,
                    decoration: InputDecoration(
                      suffixIcon: IconButton(
                        padding: EdgeInsets.all(2.0),
                        icon: Icon(
                          Icons.qr_code_scanner,
                          size: 28,
                          color: MyAppTheme.nearlyBlue,
                        ),
                        onPressed: () {
                          // requestPermissions();
                          // Utils.scanBarcode(context);
                          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
                            return ScanCode();
                          })).then((text) {
                            if (text == null) {
                              return;
                            }
                            setState(() {
                              textEditingController.text = text;
                            });
                            print(text); //拿到扫描结果
                            setSubmitNext(text);
                          });
                        },
                      ),
                      border: OutlineInputBorder(
                        borderSide: BorderSide(
                          color: MyAppTheme.nearlyBlue,
                        ),
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      enabledBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点之外的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      focusedBorder: OutlineInputBorder(
                        borderSide: BorderSide(color: MyAppTheme.nearlyBlue),
                        // 设置焦点时的边框颜色
                        borderRadius: const BorderRadius.all(Radius.circular(20.0)),
                      ),
                      hintText: codeHint,
                      filled: true,
                      fillColor: MyAppTheme.white,
                      //隐藏下划线
                      //border: InputBorder.none,
                      hintStyle: TextStyle(color: Colors.grey),
                      contentPadding: const EdgeInsets.symmetric(vertical: 0, horizontal: 15),
                    ),
                    onChanged: (text) {
                      code = text;
                    },
                  ),
                ),
              ),
            )
            // setListView()
          ],
        ),
      ),
    );
  }

  bool codeShow = true;
  String codeHint = "scan inbound lpn barcode";
  int version = 0;

  void setChange(int position) {
    if (type == position) {
      return;
    }
    type = position;

    if (data == null) {
      return;
    }
    if (data.length <= position) {
      return;
    }
    setState(() {
      switch (data[position]) {
        case "Re-Tally":
          codeShow = true;
          codeHint = "scan inbound lpn barcode";
          break;
        case "Re-Measure":
          codeShow = true;
          version = 0;
          if (Constants.jumpMapBean != null) {
            try {
              List<JumpBean> data = Constants.jumpMapBean.MANAGE_Adjustment.data;
              for (JumpBean jumpBean in data) {
                if (jumpBean.name == "ReMeasure") {
                  version = jumpBean.version;
                }
              }
            } catch (e) {
              e.printStackTrace();
            }
          }

          if (version == 2) {
            codeHint = "scan inbound lpn barcode";
          } else {
            codeHint = "scan sku/barcode";
          }
          break;
        case "CycleCount-SKU":
          codeShow = true;
          codeHint = "scan sku/barcode";
          break;
        case "CycleCount-Location":
          codeShow = true;
          codeHint = "scan location barcode";
          break;
        case "Adjust-LPN":
          codeShow = true;
          codeHint = "scan inbound lpn barcode";
          break;
        case "Merge": //隐藏
          codeShow = false;
          break;
        case "Destroy": //
          codeShow = false;
          break;
        case "Returns": //
          codeShow = true;
          codeHint = "scan inbound lpn(returns)";
          break;
        case "CycleCount-LPN":
          codeShow = true;
          codeHint = "scan inbound lpn barcode";
          break;
      }
    });
  }

  void setSubmitNext(String text) {

    switch (data[type]) {
      case "Re-Tally":
        reTallyScanLpn(text);
        break;
      case "Re-Measure":
        if (version == 2) {
          measureV2ScanLpn(text);
        } else {
          measure(text);
        }
        break;
      case "CycleCount-SKU":
        cycleCountSkuSearch(text);
        break;
      case "CycleCount-Location":
        cycleCount(text);
        break;
      case "Adjust-LPN":
        // getInventory(0, text);
        break;
      case "Merge": //隐藏
        // AppRouter.showFragmentActivity(activity, MergeActivity.class);
        break;
      case "Destroy": //
        // destoryBatch();
        break;
      case "Returns": //
        // adjustReturnsLpn(text);
        break;
      case "CycleCount-LPN":
        // returnCycleCountLpnScanLpn(text);
        break;
    }

  }
  void reTallyScanLpn(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;

    String url = Constants.reTallyScanLpn;

    int version = 0;
    try {
      if (Constants.jumpMapBean != null) {
        List<JumpBean> data = Constants.jumpMapBean.MANAGE_Adjustment.data;
        for (JumpBean jumpBean in data) {
          if (jumpBean.name =="ReTally") {
            version = jumpBean.version;
          }
        }
      }
    } catch (e) {
    e.printStackTrace();
    }
    if (version == 2) {
      url = Constants.reTally_v2_scanLpn;
    }
    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, url, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      ReTally reTally = ReTally.fromJson(baseResponse.data);
      reTally.lpn = lpn;
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => ReTallySkuScreen(reTally:reTally)),
      );
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void measure(String sku) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["sku"] = sku;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.measure, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      Measure measure = Measure.fromJson(baseResponse.data);
      measure.sku = sku;
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => ReMeasureSubmitScreen(measure:measure)),
      );
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void measureV2ScanLpn(String lpn) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["lpn"] = lpn;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.reTally_v2_scanLpn, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      ReTally reTally = ReTally.fromJson(baseResponse.data);
      reTally.lpn = lpn;
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => ReMeasureScreen(reTally:reTally)),
      );
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void cycleCountSkuSearch(String sku) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["sku"] = sku;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.cycleCountSkuSearch, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      CycleCountSku cycleCountSku = CycleCountSku.fromJson(baseResponse.data);
      if(Utils.isEmpty(cycleCountSku.sku)){
        cycleCountSku.sku = sku;
      }
      cycleCountSku.barcode = sku;
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => CCSkuScreen(cycleCountSku:cycleCountSku)),
      );
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  void cycleCount(String location) async {
    updateHint('');
    Map<String, dynamic> map = new HashMap();
    map["location"] = location;

    // 显示加载中对话框
    LoadingIndicator.show(context);

    BaseResponse baseResponse = await NetworkManager().request(context, Constants.cycleCountSkuSearch, params: map);
    // hideDialogFunction();
    // 在需要的时候隐藏加载中对话框
    LoadingIndicator.hide();

    if (baseResponse.status == 200) {
      CycleCountBean cycleCountBean = CycleCountBean.fromJson(baseResponse.data);
      if(cycleCountBean==null){
        return;
      }
      cycleCountBean.location = location;
      Navigator.push(
        context,
        MaterialPageRoute(builder: (context) => CCLocationScreen(cycleCountBean:cycleCountBean)),
      );
    } else {
      ToastContext().init(context);
      Toast.show(Utils.getStringisEmpty(baseResponse.msg), duration: Toast.lengthShort, gravity: Toast.bottom);
    }
  }

  @override
  void showFileUploadData(String path, int type, int position, bool isSubmit) {
    // TODO: implement showFileUploadData
  }

  @override
  void setNext() {
    if (Utils.isEmpty(textEditingController.text)) {
      ToastContext().init(context);
      Toast.show("scan inbound lpn barcode", duration: Toast.lengthShort, gravity: Toast.bottom);
      return;
    }
    setSubmitNext(textEditingController.text);
  }

  @override
  void setReset() {
    setState(() {
      textEditingController.text = "";
      hint = "";
    });
  }
}
